package com.hefan.api.service.activity;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.fastjson.JSON;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.common.meta.TradeLogAccountTypeEnum;
import com.cat.common.meta.TradeLogPayStatusEnum;
import com.cat.common.meta.UserTypeEnum;
import com.cat.common.util.GuuidUtil;
import com.cat.common.util.RandomUtil;
import com.hefan.activity.bean.HfActivityAttend;
import com.hefan.activity.bean.HfActivityCfgAttr;
import com.hefan.activity.bean.HfActivityCfgInfo;
import com.hefan.api.service.UserLocalService;
import com.hefan.oms.itf.ExpendService;
import com.hefan.pay.bean.TradeLog;
import com.hefan.pay.itf.TradeLogService;
import com.hefan.user.bean.WebUser;
import com.hefan.user.itf.WebUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lxw on 2016/11/29.
 */
@Component
public class ConferenceActivityLocalService {

    private Logger logger = LoggerFactory.getLogger(ConferenceActivityLocalService.class);

    @Resource
    private UserLocalService userLocalService;

    @Resource
    private HfActivityHandlerLocalService hfActivityHandlerLocalService;

    @Reference
    private WebUserService webUserService;

    @Reference
    private TradeLogService tradeLogService;

    @Reference
    private ExpendService expendService;

    /**
     * 获取发布会活动页面显示数据
     * @param userId
     * @param activityId
     * @return
     */
    public ResultBean getConferenceActivityPageShow(String userId,int activityId) {
        ResultBean res = new ResultBean(ResultCode.SUCCESS, null);
        Map resMap = new HashMap();
        //检查用户信息
        WebUser webUser = userLocalService.getWebUserByUserId(userId);
        if(webUser == null) {
            return new ResultBean(ResultCode.LoginUserIsNotExist, null);
        }
        if(UserTypeEnum.isVirtualUser(webUser.getUserType())) {  //虚拟用户不能进行该操作
            return new ResultBean(ResultCode.VirtualUserNotOpreate,null);
        }
        //获取活动对象
        HfActivityCfgInfo hfActivityCfgInfo = hfActivityHandlerLocalService.findActivityCfg(activityId);
        //检查抽检活动是否有效
        res =  hfActivityHandlerLocalService.checkActivityIsValid(hfActivityCfgInfo);
        if(res.getCode() != ResultCode.SUCCESS.get_code()) {
            return res;
        }
        //获取活动期间消费的饭票数-------
        long consumeFanPiao = expendService.findUserExpendFianpiao(userId,hfActivityCfgInfo.getBeginDate(),hfActivityCfgInfo.getEndDate());
        int attendNum = hfActivityHandlerLocalService.findActivityAttendNum(activityId, userId);
        //计算可抽奖次数
        long validAttendNum = consumeFanPiao/500 - attendNum;
        resMap.put("consumeFanPiao",consumeFanPiao);
        resMap.put("attendNum",validAttendNum);
        res.setData(resMap);
        return res;
    }

    /**
     * 保存发布会活动抽奖信息
     * @param userId
     * @param activityId
     * @return
     */
    public ResultBean saveActivityAttendOprate(String userId, long activityId) {
        ResultBean res = new ResultBean(ResultCode.SUCCESS, null);
        Map resMap = new HashMap();

        //检查是否频繁请求
        if(hfActivityHandlerLocalService.activityFrequentlyReqCheck(userId,activityId) == 1) {
            return  new ResultBean(ResultCode.ActivityFrequentlyReq, null);
        }
        //增加频繁操作检查key到缓存
        hfActivityHandlerLocalService.setActivityFrequentlyReqCach(userId,activityId);

        //检查用户信息
        WebUser webUser = userLocalService.getWebUserByUserId(userId);
        if(webUser == null) {
            return new ResultBean(ResultCode.LoginUserIsNotExist, null);
        }
        if(UserTypeEnum.isVirtualUser(webUser.getUserType())) {  //虚拟用户不能进行该操作
            return new ResultBean(ResultCode.VirtualUserNotOpreate,null);
        }

        //获取活动对象
        HfActivityCfgInfo hfActivityCfgInfo = hfActivityHandlerLocalService.findActivityCfg(activityId);
        //检查抽检活动是否有效
        res =  hfActivityHandlerLocalService.checkActivityIsValid(hfActivityCfgInfo);
        if(res.getCode() != ResultCode.SUCCESS.get_code()) {
            return res;
        }

        
        //获取活动期间消费的饭票数-------
        long consumeFanPiao = expendService.findUserExpendFianpiao(userId,hfActivityCfgInfo.getBeginDate(),hfActivityCfgInfo.getEndDate());
        int attendNum = hfActivityHandlerLocalService.findActivityAttendNum(activityId, userId);
        //计算可抽奖次数
        long validAttendNum = consumeFanPiao/500 - attendNum;
        int rand = -1;
        if(validAttendNum -1 >= 0) {
            rand = RandomUtil.getRandom(1,101); //1-100的随机数
            HfActivityCfgAttr hfActivityCfgAttr = null;
            if(rand <=70) {  //中奖区域
                //获取有效的奖品列表
                List<HfActivityCfgAttr> avlidAttrList =  hfActivityHandlerLocalService.findAvlidActivitCfgAttrList(activityId);
                hfActivityCfgAttr =  getActivityAttrInfo(avlidAttrList);
            }
              int incrFlag = 0;
            if(hfActivityCfgAttr != null) { //已中奖
                //对奖项有效数减1
                incrFlag = hfActivityHandlerLocalService.incrActivityAttrAvlidNum(activityId,hfActivityCfgAttr.getId(),-1);
            }
            logger.info("saveActivityAttendOprate------------------------incrFlag:"+incrFlag);
            if(incrFlag == 0) { //组装未中奖的属性信息
                hfActivityCfgAttr = new HfActivityCfgAttr();
                hfActivityCfgAttr.setId(-1);
                hfActivityCfgAttr.setActivityId(3);
                hfActivityCfgAttr.setAttrType(0);
                hfActivityCfgAttr.setAttrVal(0L);
            }
            HfActivityAttend hfActivityAttend = saveActivityAttendOprate(hfActivityCfgInfo,webUser,hfActivityCfgAttr,rand);
            res.setData(hfActivityAttend);
        } else  {
            res =  new ResultBean(ResultCode.ActivityAttendNext,null);
        }
        return res;
    }

    /**
     * 保存奖励操作
     * @param hfActivityCfgInfo
     * @param webUser
     * @param hfActivityCfgAttr
     * @return
     */
    private HfActivityAttend saveActivityAttendOprate(HfActivityCfgInfo hfActivityCfgInfo,WebUser webUser,HfActivityCfgAttr hfActivityCfgAttr, int wardRandNum) {
        HfActivityAttend hfActivityAttend = null;
        if(hfActivityCfgAttr.getAttrType() == 1) { //成长值奖励
            hfActivityAttend = saveExpAward(hfActivityCfgInfo,webUser,hfActivityCfgAttr, wardRandNum);
        } else if(hfActivityCfgAttr.getAttrType() == 2) { //饭票奖励
            hfActivityAttend = saveFanpiaoAward(hfActivityCfgInfo,webUser,hfActivityCfgAttr, wardRandNum);
        }
        if(hfActivityAttend == null) { //反不中奖记录
            //保存活动参加信息
            hfActivityAttend = new HfActivityAttend();
            hfActivityAttend.setActivityId(hfActivityCfgAttr.getActivityId());
            hfActivityAttend.setActivityAttrType(hfActivityCfgAttr.getAttrType());
            hfActivityAttend.setActivityAttrId(hfActivityCfgAttr.getId());
            hfActivityAttend.setUserId(webUser.getUserId());
            hfActivityAttend.setGiveNum(Integer.valueOf(String.valueOf(hfActivityCfgAttr.getAttrVal())));
            hfActivityAttend.setExtId("");
            hfActivityAttend.setExtData(webUser.getNickName());
            hfActivityAttend.setExtNum(String.valueOf(wardRandNum));
            hfActivityHandlerLocalService.saveActivityAttendInfo(hfActivityAttend);
        }
        return hfActivityAttend;
    }

    /**
     * 保存饭票奖品信息
     * @param hfActivityCfgInfo
     * @param webUser
     * @param hfActivityCfgAttr
     * @return
     */
    private HfActivityAttend saveFanpiaoAward(HfActivityCfgInfo hfActivityCfgInfo,WebUser webUser,HfActivityCfgAttr hfActivityCfgAttr, int wardRandNum) {
        //新增用户饭票
        int rowNum = webUserService.incrWebUserBalance(webUser.getUserId(),hfActivityCfgAttr.getAttrVal());
        if(rowNum > 0) {
            //保存充值信息
            TradeLog tradeLog = new TradeLog();
            tradeLog.setOrderId(GuuidUtil.getUuid());
            tradeLog.setUserId(webUser.getUserId());
            tradeLog.setUserType(webUser.getUserType());
            tradeLog.setNickName(webUser.getNickName());
            tradeLog.setPayAmount(new BigDecimal(0));
            tradeLog.setIncome(0);
            tradeLog.setExchangeAmount(new BigDecimal(0));
            tradeLog.setChannelFee(new BigDecimal(0));
            tradeLog.setPlatformCost(new BigDecimal(0));
            tradeLog.setIncomeAmount(Integer.valueOf(String.valueOf(hfActivityCfgAttr.getAttrVal())));
            tradeLog.setRewardFanpiao(Integer.valueOf(String.valueOf(hfActivityCfgAttr.getAttrVal())));
            tradeLog.setAccountType(TradeLogAccountTypeEnum.ACTIVITY_ACCOUNT_TYPE.getAccountType());
            tradeLog.setPaySource(0);
            tradeLog.setPayBeforeFanpiao(webUser.getBalance());
            tradeLog.setPayAfterFanpiao(webUser.getBalance()+hfActivityCfgAttr.getAttrVal());
            tradeLog.setPayStatus(TradeLogPayStatusEnum.PAY_SUCCESS.getPayStatus());
            tradeLog.setPaymentExtend(JSON.toJSONString(hfActivityCfgAttr));
            tradeLog.setPaymentType(0);
            tradeLog.setThirdPartyTradeNo(String.valueOf(hfActivityCfgInfo.getId()));
            long tradLogId = tradeLogService.saveAndCalTradeLog(tradeLog);
            //保存活动参加信息
            HfActivityAttend hfActivityAttend = new HfActivityAttend();
            hfActivityAttend.setActivityId(hfActivityCfgAttr.getActivityId());
            hfActivityAttend.setActivityAttrType(hfActivityCfgAttr.getAttrType());
            hfActivityAttend.setActivityAttrId(hfActivityCfgAttr.getId());
            hfActivityAttend.setUserId(webUser.getUserId());
            hfActivityAttend.setGiveNum(Integer.valueOf(String.valueOf(hfActivityCfgAttr.getAttrVal())));
            hfActivityAttend.setExtId(tradeLog.getOrderId());
            hfActivityAttend.setExtData(webUser.getNickName());
            hfActivityAttend.setExtNum(String.valueOf(wardRandNum));
            hfActivityHandlerLocalService.saveActivityAttendInfo(hfActivityAttend);
            return hfActivityAttend;
        }
        return null;
    }

    /**
     * 保存成长值
     * @param hfActivityCfgInfo
     * @param webUser
     * @param hfActivityCfgAttr
     * @return
     */
    private HfActivityAttend saveExpAward(HfActivityCfgInfo hfActivityCfgInfo,WebUser webUser,HfActivityCfgAttr hfActivityCfgAttr,int wardRandNum) {
        //保存成长值
        ResultBean res = webUserService.userLevelOprate(webUser.getUserId(),hfActivityCfgAttr.getAttrVal());
        if(res.getCode() == ResultCode.SUCCESS.get_code()) {
            //保存活动参加信息
            HfActivityAttend hfActivityAttend = new HfActivityAttend();
            hfActivityAttend.setActivityId(hfActivityCfgAttr.getActivityId());
            hfActivityAttend.setActivityAttrType(hfActivityCfgAttr.getAttrType());
            hfActivityAttend.setActivityAttrId(hfActivityCfgAttr.getId());
            hfActivityAttend.setUserId(webUser.getUserId());
            hfActivityAttend.setGiveNum(Integer.valueOf(String.valueOf(hfActivityCfgAttr.getAttrVal())));
            hfActivityAttend.setExtId("");
            hfActivityAttend.setExtData(webUser.getNickName());
            hfActivityAttend.setExtNum(String.valueOf(wardRandNum));
            hfActivityHandlerLocalService.saveActivityAttendInfo(hfActivityAttend);
            return hfActivityAttend;
        }
        return null;
    }

    /**
     * 获取抽中奖品的对象
     */
    private HfActivityCfgAttr getActivityAttrInfo(List<HfActivityCfgAttr> avlidAttrList) {
        logger.info("getActivityAttrInfo ---------"+avlidAttrList.size());
        long sumMax = 0;
        if(avlidAttrList != null && avlidAttrList.size()>0) {
            for (HfActivityCfgAttr obj:avlidAttrList) {
                sumMax = sumMax+obj.getAttrAvlidVal();
            }
            logger.info("getActivityAttrInfo ---------sumMax:"+sumMax);
            if(sumMax > 0) {
                long startNum = 1L;
                long randomNum = RandomUtil.getRandom(startNum,sumMax+1);
                logger.info("getActivityAttrInfo ---------randomNum:"+randomNum);
                long minVal = 0L;
               for(int i=0; i<avlidAttrList.size(); i++) {
                   HfActivityCfgAttr attrObjTemp = avlidAttrList.get(i);
                   if(i>0) {
                       minVal = minVal+avlidAttrList.get(i-1).getAttrAvlidVal();
                   }
                   if(minVal<randomNum && randomNum<=minVal+attrObjTemp.getAttrAvlidVal()) {
                       logger.info("getActivityAttrInfo ---------attrId:"+attrObjTemp.getId());
                       return attrObjTemp;
                   }
               }
            }
        }
        return  null;
    }


    public static void main(String[] args) {
        long consumeFp = 999l;
        int attedNum = 0;

        System.out.println(consumeFp/500 - attedNum);

    }
}
